package top.healthylife.pangwa.client;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import java.util.HashMap;
import java.util.Map;

/**
 * @author Gaozexi on 2020/5/20 19:42
 * Step by Step  and Stand on,  You Are The Best Investment!
 */

public class MyRestTemplate extends RestTemplate {
    @Value("${pangwa.server.host:localhost}")
    private String serverHost;
    @Value("${pangwa.server.port:1688}")
    private int serverPort;
    @Autowired
    private Map<String,Object> cacheMap;
    @Autowired
    private MyRestTemplate myRestTemplate;

    private Logger logger = LoggerFactory.getLogger(MyRestTemplate.class);
    public String pullService(String serviceName){
        if(cacheMap.keySet().contains(serviceName.toUpperCase())){
            //已存在缓存数据
            String ipAndPortInfo = (String) cacheMap.get(serviceName.toUpperCase());
            logger.info("Use cache data");
            return ipAndPortInfo;
        }else {
            //缓存不存在,发送远程请求,并缓存数据
            logger.info("No Cache , will send  remote request");
            String getDataUrl = "http://"+serverHost+":"+serverPort+"/dispatch/"+serviceName.toUpperCase();
            String ipAndPortInfo = myRestTemplate.getForObject(getDataUrl, String.class);
            cacheMap.put(serviceName.toUpperCase(),ipAndPortInfo);
            return ipAndPortInfo;
        }
    }


}
